﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Navigation;

namespace ComToolkit.Demo.Views
{
    public partial class Data : Page
    {
        ComToolkit.Data.AdoConnection connection;
        public Data()
        {
            InitializeComponent();
            ConnectionString.Text = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=C:\ComToolkit\;Extensions=asc,csv,tab,txt;";
            SqlQuery.Text = "SELECT TOP 10 * FROM [countrylist.csv]";
            ExecuteSqlQuery.IsEnabled = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            
        }

        private void ButtonConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                connection = new ComToolkit.Data.AdoConnection(ConnectionString.Text);
                connection.Open();
                ExecuteSqlQuery.IsEnabled = true;
                MessageBox.Show("Connection success!");
            }
            catch(Exception ex)
            {
                ExecuteSqlQuery.IsEnabled = false;
                MessageBox.Show(ex.ToString());
            }
        }

        private void ExecuteSqlQuery_Click(object sender, RoutedEventArgs e)
        {
            Execute();
        }

        private void Execute()
        {
            try
            {
                DataGridResult.Columns.Clear();
                var command = connection.CreateCommand();
                command.CommandText = SqlQuery.Text;
                IEnumerable<Dictionary<string, object>> rows = null;
                using (var reader = command.ExecuteReader())
                {
                    rows = reader.GetRows();
                }
                if (rows.Count() > 0)
                {
                    foreach (var col in rows.First())
                    {
                        DataGridResult.Columns.Add(new System.Windows.Controls.DataGridTextColumn()
                        {
                            Header = col.Key,
                            Binding = new System.Windows.Data.Binding()
                                {
                                    Converter = new ComToolkit.Demo.Converters.DictionaryValueConverter(),
                                    ConverterParameter = col.Key
                                }
                        });
                    }
                }
                DataGridResult.ItemsSource = rows;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    }
}
